package com.citms.aif.util;

import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RestTemplateUtils {

	/**
	 * json 转 httpEntity
	 *
	 * @param json
	 * @return
	 */
	public static HttpEntity<String> getHttpEntity(String json, HttpServletRequest request,String reqUrl) {
		// 拿到header信息
		HttpHeaders requestHeaders = new HttpHeaders();
		//requestHeaders.setContentType(MediaType.APPLICATION_JSON);// text/css
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {

			String key = (String) headerNames.nextElement();

			if (key.startsWith("accept")) {
				continue;
			}
			String value = request.getHeader(key);
			requestHeaders.add(key, value);
		}
		URI uri = URI.create(reqUrl);
		requestHeaders.setHost(InetSocketAddress.createUnresolved(uri.getHost(), uri.getPort() == -1?80:uri.getPort()));
		HttpEntity<String> httpEntity = new HttpEntity<String>(json, requestHeaders);
		
		return httpEntity;
	}

	/**
	 * 请求参数，请求头，转 httpEntity
	 *
	 * @return
	 */
	public static HttpEntity<String> getHttpEntity(Object params, Map<String, String> heads,String reqUrl) {
		
		String json = null;
		if (params != null) {
			json = JsonUtil.beanToString(params);
		}
		return getHttpEntity(json,heads,reqUrl);
		
	}
	
	/**
	 * json 转 httpEntity
	 *
	 * @param json
	 * @return
	 */
	public static HttpEntity<String> getHttpEntity(String json, Map<String, String> heads,String reqUrl) {
		// 拿到header信息
		HttpHeaders requestHeaders = new HttpHeaders();
		requestHeaders.setContentType(MediaType.APPLICATION_JSON);// text/css
		for (String key : heads.keySet()) {
			String value = heads.get(key);
			requestHeaders.add(key, value);
		}
		URI uri = URI.create(reqUrl);
		requestHeaders.setHost(InetSocketAddress.createUnresolved(uri.getHost(), uri.getPort()==-1?80:uri.getPort()));
		HttpEntity<String> httpEntity = new HttpEntity<String>(json, requestHeaders);
		return httpEntity;
	}


}
